/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable import/no-extraneous-dependencies */
import { routerRedux } from 'dva/router';
import { message } from 'antd';
import { stringify } from 'qs';
import { reloadAuthorized } from '@/utils/Authorized';
import { getPageQuery } from '@/utils/utils';
import { accountLogin, accountLogout } from '../services/user';

const isLoginPage = url => url.includes('/user/login');
export default {
  namespace: 'login',

  state: {
    status: undefined,
    refresh: false,
  },

  effects: {
    *login({ payload, then }, { call, put }) {
      const response = yield call(accountLogin, payload);
      if (!response) {
        return;
      }
      const { code, msg, data } = response;
      // Login successfully
      if (code == 0) {
        yield put({
          type: 'changeLoginStatus',
          payload: {
            ...data,
          },
        });
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let { redirect } = params;
        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            if (isLoginPage(redirect)) {
              redirect = '/';
            } else {
              redirect = redirect.substr(urlParams.origin.length);
              if (redirect.startsWith('/#')) {
                redirect = redirect.substr(2);
              }
            }
          } else {
            window.location.href = redirect;
            return;
          }
        }

        yield put(routerRedux.replace(redirect || '/'));
      } else {
        message.error(msg, [2]);
      }
      if (msg == '验证码错误') {
        then(code);
      }
    },
    *logout({ payload }, { call, put }) {
      // 已经在登录页，防止重复跳转登录页
      if (isLoginPage(window.location.href)) {
        return;
      }
      const response = yield call(accountLogout, payload);
      if (!response) {
        return;
      }
      const { code } = response;
      if (code == 0) {
        yield put({
          type: 'changeLoginStatus',
          payload: {
            status: false,
          },
        });
        reloadAuthorized();
        window.location.href = `/user/login?${stringify({
          redirect: window.location.href,
        })}`;
      }

      // yield put(
      //   routerRedux.push({
      //     pathname: "/user/login",
      //     search: stringify({
      //       redirect: window.location.href
      //     })
      //   })
      // );
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      return {
        ...state,
        status: payload.status,
        type: payload.type,
      };
    },
  },
};
